import { reactive } from 'vue'
// import { usePortsStore } from '@renderer/stores/portsStore'
// const portsStore = usePortsStore()

// hooks
import { useMessage } from '@renderer/hooks/message'
import { useCommonTools } from '@renderer/hooks/commonTools'
const messageTip = useMessage()
const commonTools = useCommonTools()

// const appInstance = getCurrentInstance()?.appContext.app;
// const globalPortsStore = appInstance?.config.globalProperties.$globalPortsStore;
// console.log('globalPortsStore', globalPortsStore)

export function useOfflineBurningMode() {
    const burnFileList = reactive([
        {
            fileName: 'BOOT文件',
            fileUrl: 'http://file.riding-evolved.com/20221217/1671242186/B_JH_FW_BL_DT_BC280_V2.2.2.bin',
            isActive: false,
            version: 'v1.0.0',
            versionInfo: '',
            percent: 0,
            responseType: 'arraybuffer',
            fileType: 1,
            byteData: [] as any[],
            rawData: [] as any[]
        },
        {
            fileName: 'APP文件',
            // fileUrl: 'http://file.riding-evolved.com/20221121/1669012416/B_JH_FW_APP_DT_BC280_V2.3.0.hex',
            // fileUrl: 'http://file.riding-evolved.com/20240802/1722569745/B_CM_FW_APP_DT_A6LM_V1.0.46.bin',
            // fileUrl: 'http://file.riding-evolved.com/20230711/1689060816/B_CM_FW_APP_DT_BC300_V6.0.21.bin',
            fileUrl: 'http://file.riding-evolved.com/20230712/1689147213/B_CM_FW_APP_DT_BC300_V62.2.22.bin',
            isActive: false,
            version: 'v1.0.0',
            versionInfo: '',
            percent: 0,
            responseType: 'arraybuffer',
            fileType: 2,
            byteData: [] as any[],
            rawData: [] as any[]
        },
        {
            fileName: 'UI文件',
            // fileUrl: 'http://file.riding-evolved.com/20221020/1666260572/BC280UL_JiaHong_UI_V2.304.txt',
            fileUrl: 'http://file.riding-evolved.com/20230717/1689557441/P_CM_UI_JC_BC301_V0.1.bin',
            isActive: false,
            version: 'v1.0.0',
            versionInfo: '',
            percent: 0,
            responseType: 'arraybuffer',
            fileType: 4,
            byteData: [] as any[],
            rawData: [] as any[]
        },
        {
            fileName: '车型配置文件',
            fileUrl: 'http://file.riding-evolved.com/fileLoad/20240607152454.json',
            isActive: false,
            isSee: true,
            versionInfo: '',
            percent: 0,
            fileType: 8,
            byteData: [] as any[],
            rawData: [] as any[]
        }
    ])

    const clearUpgradTypeFn = (dataHex) => {
        // 清空项   1-Boot；2-APP；4-UI；8-配置文件
        const clearType = dataHex[3]
        // 清空结果  0: 失败  1： 成功
        const clearResult = dataHex[4]

        switch (clearType) {
            // boot
            case 1:
                upgradFeedBack(0, 0x32, clearType, clearResult)
                break
            // APP
            case 2:
                upgradFeedBack(1, 0x33, clearType, clearResult)
                break
            // UI
            case 4:
                upgradFeedBack(2, 0x31, clearType, clearResult)
                break
            // 配置文件
            // case 8: upgradFeedBack(3, 0x30, clearResult); break;
        }
    }

    const clearTypeErrTip = {
        1: 'Boot',
        2: 'APP',
        4: 'UI',
        8: '配置文件'
    }

    const upgradFeedBack = (fileTypeIndex, CMD_ADDRESS, clearType, clearResult) => {
        console.log('fileTypeIndex, CMD_ADDRESS, clearType, clearResult', fileTypeIndex, CMD_ADDRESS, clearType, clearResult)
        if (clearResult === 1) {
            upgradFile(fileTypeIndex, CMD_ADDRESS)
        } else {
            messageTip.error(`${clearTypeErrTip[clearType]}清空缓冲区失败`)
        }
    }

    // 升级文件
    const upgradFile = async (fileTypeIndex, CMD_ADDRESS) => {
        const byteData = burnFileList[fileTypeIndex].byteData

        console.log('升级文件', fileTypeIndex, CMD_ADDRESS, byteData)

        for (let i = 0; i < byteData.length; i++) {
            // portsStore.writeMsg(portsStore.cmdSum(CMD_ADDRESS, byteData[i]))
        }
    }

    let appBagCount = 0;
    let uiBagCount = 0;
    let bootBagCount = 0;
    let configBagCount = 0;

    /**
     * 
     * @param dataHex 串口返回的数据
     * @param fileTypeIndex 原数据类型下标 0 - Boot, 1 - APP, 2 - UI, 3 - 配置
     * @param clearType 清空项类型 1-Boot；2-APP；4-UI；8-配置文件。
     * @returns 
     */
    const upgradOfflineFileFn = (dataHex, fileTypeIndex, clearType, CMD_ADDRESS) => {
        // 0： 失败  非0: 成功
        const result = dataHex[3];
        if (result === 0) {
            messageTip.error(`${clearTypeErrTip[clearType]} 数据写入失败`)
            return;
        }

        switch (CMD_ADDRESS) {
            // 配置
            case 0x30: configBagCount++; break;
            // UI
            case 0x31: uiBagCount++; break;
            // Boot
            case 0x32: bootBagCount++; break;
            // app
            case 0x33: appBagCount++; break;
        }

        const bagCount = {
            0x30: configBagCount,
            0x31: uiBagCount,
            0x32: bootBagCount,
            0x33: appBagCount,
        }

        console.log(`${clearTypeErrTip[clearType]}写入成功`)

        const byteData = burnFileList[fileTypeIndex].byteData

        burnFileList[fileTypeIndex].percent = commonTools.calculateProgress(bagCount[CMD_ADDRESS], byteData.length)
        console.log(`升级文件百分比:, ${burnFileList[fileTypeIndex].percent}`)
        if (burnFileList[fileTypeIndex].percent === 100) {
            upgradEnd(fileTypeIndex)
        }
    }

    const upgradEnd = (fileTypeIndex) => {
        const CMD_ADDRESS = 0x34
        let upgradEndType: number = 0 //  【结束项】0-BOOT，1-APP，2-UI， 3-config
        switch (fileTypeIndex) {
            case 0:
                upgradEndType = 0
                break
            case 1:
                upgradEndType = 1
                break
            case 2:
                upgradEndType = 2
                break
            case 3:
                upgradEndType = 3
                break
        }

        const fileUrl = burnFileList[fileTypeIndex].fileUrl
        const fileName = commonTools.getFileExtensionFromUrl(fileUrl, true)
        const fileTypeName = commonTools.stringToHexArray(fileName)
        // portsStore.writeMsg(portsStore.cmdSum(CMD_ADDRESS, [upgradEndType, fileName.length, ...fileTypeName]))
    }

    const getUpgradEndFn = (dataHex, CMD_ADDRESS) => {
        if (CMD_ADDRESS === 0x34) {
            const upgradEndResult = dataHex[3]
            const upgradWriteEnd = dataHex[4]

            upgradEndTip(upgradEndResult, upgradWriteEnd)
        }
    }

    const upgradEndTypeObj = {
        0: 'Boot',
        1: 'APP',
        2: 'UI',
        3: '配置文件'
    }
    const upgradEndTip = (upgradEndResult, upgradWriteEnd) => {
        if (upgradWriteEnd !== 0) {
            console.log(`${upgradEndTypeObj[upgradEndResult]} 升级结束写入成功`)
        } else {
            console.log(`${upgradEndTypeObj[upgradEndResult]} 升级结束写入失败`)
        }
    }

    return {
        burnFileList,
        clearUpgradTypeFn,
        upgradOfflineFileFn,
        getUpgradEndFn
    }
}